﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.Modeling.Validation;

namespace Microsoft.Samples.DslTools.ConfigurationSectionDesigner
{
    [ValidationState( ValidationState.Enabled )]
    public partial class ConfigurationSection
    {
        #region Convenience Properties

        /// <summary>
        /// Gets a full documentation text based on the user-given <see cref="Documentation"/>.
        /// </summary>
        /// <remarks>
        /// If no user-given documentation is present, a "good enough" default description is returned.
        /// </remarks>
        public override string DocumentationText
        {
            get
            {
                return (string.IsNullOrEmpty( this.Documentation ) ? string.Format( "The {0} Configuration Section.", this.Name ) : this.Documentation);
            }
        }

        #endregion

        #region Automatically Set XML Name

        protected override void OnNameChanged( EventArgs e )
        {
            // When the name changes, set the XML name to the same name but camelCased.
            this.XmlSectionName = NamingHelper.ToCamelCase( this.Name );

            // Always call the base class method.
            base.OnNameChanged( e );
        }

        #endregion

        #region Validation

        /// <summary>
        /// Validates the XML Name.
        /// </summary>
        /// <param name="context">The validation context.</param>
        [ValidationMethod( ValidationCategories.Menu | ValidationCategories.Open | ValidationCategories.Save )]
        private void ValidateXmlName( ValidationContext context )
        {
            if( string.IsNullOrEmpty( this.XmlSectionName ) )
            {
                context.LogError( "The Xml Section Name is required and cannot be an empty string.", "RequiredProperty", this );
            }
        }

        /// <summary>
        /// Validates the custom section provider.
        /// </summary>
        /// <param name="context">The validation context.</param>
        [ValidationMethod( ValidationCategories.Menu | ValidationCategories.Open | ValidationCategories.Save )]
        private void ValidateCustomSectionProvider( ValidationContext context )
        {
            if( (this.CodeGenOptions & ConfigurationSectionCodeGenOptions.Protection) == ConfigurationSectionCodeGenOptions.Protection )
            {
                if( this.ProtectionProvider == ProtectionProviders.Custom )
                {
                    if( string.IsNullOrEmpty( this.CustomProtectionProvider ) )
                    {
                        context.LogError( "The Custom Protection Provider cannot be an empty string when the Protection Provider is set to 'Custom'", "CustomProviderNotSet", this );
                    }
                }
            }
        }

        #endregion
    }
}